/*
 * ProcessAux.cpp
 *
 */

#include "ProcessAux.h"
#include <iostream>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "../mariano/comun/CPrinter.h"
#include <rpc/rpc.h>

pidList_t ProcessAux::m_PidList;

pidList_t ProcessAux::launchProcess(std::string procPath,int numberOfProc,
		Argv arguments )
{
	pidList_t result;
	std::string error;

	for(int i=1;i<=numberOfProc;i++)
	{
		Argv current_arguments = arguments;
		current_arguments.pushArg(procPath,Argv::PUSH_FRONT);
		int status;

		pid_t pid2;
		pid_t pid = fork();

		// Doing double fork to avoid zombie processes
		if(pid == 0)
		{ // Intermediate child (will die)
			pid2 = fork();
			if (pid2 == 0)
			{
				// True child, will do some stuff and die cleanly
				if(execve(procPath.c_str(),current_arguments.getArgv(),NULL))
				{
					error = strerror( errno );
					std::cerr << "Error al cargar el codigo del proceso '"
							<< procPath.c_str() << "': "
							<< error << std::endl;
					exit(1);
				}
			} else {
				exit(0);
			}
		}
		else
		{ // Parent process, will do some stuff and wait for his childs
			waitpid(pid, &status, WUNTRACED | WCONTINUED);
		}
	}
	return result;
}
void ProcessAux::launchProcess2(std::string procPath,int numberOfProc,
		Argv arguments, unsigned int sdelay )
{
	std::string error;

	for(int i=1;i<=numberOfProc;i++)
	{
		Argv current_arguments = arguments;

		current_arguments.pushArg(procPath,Argv::PUSH_FRONT);

		sleep( sdelay );

		pid_t pid = fork();
		if(pid <0)
		{
			error = strerror( errno );
			std::cerr << "Error al iniciar el proceso '"
					<< procPath.c_str() << "': "
					<< error << std::endl;
			exit(1);
		}
		else
		{
			if(!pid)
			{
				if(execve(procPath.c_str(),current_arguments.getArgv(),NULL))
				{
					error = strerror( errno );
					std::cerr << "Error al cargar el codigo del proceso '"
							<< procPath.c_str() << "': "
							<< error << std::endl;
					exit(1);
				}
			}
			else
				m_PidList.push_back(pid);
		}
	}
}


